<template> 
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <!-- <i class="el-icon-search"></i>
        <span>筛选搜索</span> -->

      </div>
      <div style="display: flex;align-items: center;justify-content: center;">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="输入搜索：" style="margin: 0 10px 0 0;">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="帐号/姓名" clearable></el-input>
          </el-form-item>
        </el-form>

        <el-button

          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button

          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <!-- <i class="el-icon-tickets"></i> -->
      <!-- <span>数据列表</span> -->
      <el-button size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加账号</el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="adminTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column label="姓名" width="100" align="center">
          <template slot-scope="scope">
            <!-- {{scope.row.nickName}} -->
            <div v-html="hightLight(listQuery.keyword, scope.row.nickName)"></div>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template slot-scope="scope">{{scope.row.note}}</template>
        </el-table-column>
        <el-table-column label="角色" align="center">
          <template slot-scope="scope">{{dealName(scope.row.roleList)}}</template>
        </el-table-column>
        <el-table-column label="是否启用" align="center">
          <template slot-scope="scope">{{scope.row.status ? '启用' : '禁用'}}</template>
        </el-table-column>
        <el-table-column label="添加时间" width="160" align="center">
          <template slot-scope="scope">{{scope.row.createTime | formatDateTime}}</template>
        </el-table-column>
        <el-table-column label="最近上线时间" width="160" align="center">
          <template slot-scope="scope">{{scope.row.loginTime | formatDateTime}}</template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="text"
                       @click="handleUpdate(scope.$index, scope.row)">
              管理
            </el-button>
            <el-button v-if="scope.row.id !== 1" size="mini"
                       type="text"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="'添加/管理员工账号用户'"
      :visible.sync="dialogVisible"
      width="60%">
      <el-form :model="admin"
               ref="adminForm"
               label-width="150px" size="small">
        <el-form-item label="选择团队成员：">
          <el-select v-model="admin.feiShuOpenId" clearable
            filterable
            remote
            :disabled='isEdit'
            :remote-method="getNameData"
            :loading="loading" placeholder="请搜索"  >
            <el-option
              v-for="item in optionsName"
              :key="item.userId"
              :label="item.name"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="添加备注：">
          <el-input v-model="admin.note" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="分配角色：">
          <el-select v-model="admin.roleIdList" multiple placeholder="请选择" size="small" style="width: 60%">
            <el-option
              v-for="item in allRoleList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用：">
          <el-radio-group v-model="admin.status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
  import { updateStatus,deleteAdmin } from '@/api/login';
  import { fetchAllRoleList } from '@/api/role';
  import { formatDate } from '@/utils/date';
  import { sysList, sysDelete, sysAdd, sysUpdate, getNameRole, fetchAllResourceList } from '@/api/app';

  const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    keyword: null
  };
  const defaultAdmin = {
    feiShuOpenId: null,
    note: null,
    roleIdList: [],
    status: 1,
  };
  export default {
    name: 'adminList',
    data() {
      return {
        listQuery: Object.assign({}, defaultListQuery),
        list: null,
        total: null,
        listLoading: false,
        dialogVisible: false,
        admin: Object.assign({}, defaultAdmin),
        isEdit: false,
        allRoleList:[],
        allocAdminId:null,
        optionsName: [],
        loading: false,
        updateQuery: {
          id: null,
          note: null,
          roleIdList: [],
          status: 1,
        },
        btnMenu: {
          edit: true,
          delete: true,
        },
      }
    },
    created() {
      const menu = JSON.parse(localStorage.getItem('listMenu'));
      const item = menu.filter(item => item.title === '系统账号')[0];
      fetchAllResourceList({menuId: item.id }).then(res => {
        res.data.forEach(dom => {
          if (dom.component === '' && dom.name === '后台用户管理') {
            this.btnMenu.edit = false;
          }
          if (dom.component === '' && dom.name === '后台用户删除') {
            this.btnMenu.delete = false;
          }
        });
      });
      this.getList();
      this.getAllRoleList();
    },
    filters: {
      formatDateTime(time) {
        if (time == null || time === '') {
          return '-';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    methods: {
      hightLight (keyWord, suggtion) {
            // 使用 regexp 构造函数，因为这里要匹配的是一个变量
            let newSrt = null;
            const reg = new RegExp(keyWord, 'ig')
            if (keyWord && suggtion) {
                newSrt = String(suggtion).replace(reg, function (p) {
                    return '<span style="color: #409EFF">' + p + '</span>'
                })
            } else {
                newSrt = suggtion;
            }
            return newSrt
        },
      getNameData(key) {
        if (key) {
          this.loading = true;
          // console.log(key);
          getNameRole({name: key}).then(res => {
            // console.log(res);
            this.optionsName = res.data;
            this.loading = false;
          });
        }
      },
      dealName(list) {
        let name = '';
        list.forEach(item => {
          name += item.name + ',';
        });
        return name;
      },
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
        this.getList();
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleAdd() {
        this.dialogVisible = true;
        this.isEdit = false;
        this.admin = Object.assign({},defaultAdmin);
      },
      handleStatusChange(index, row) {
        this.$confirm('是否要修改该状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus(row.id, {status: row.status}).then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消修改'
          });
          this.getList();
        });
      },
      handleDelete(index, row) {
        if (this.btnMenu.delete) {
          this.$confirm('是否要删除该帐号?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            sysDelete(row.id).then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList();
            });
          });
        } else {
          this.$message({
            type: 'error',
            message: '无权限操作'
          });
        }
      },
      handleUpdate(index, row) {
        if (this.btnMenu.delete) {
          this.admin = Object.assign({}, defaultAdmin);
          this.optionsName = [{
            employeeNo: null,
            employeeType: null,
            id: row.id,
            name: row.nickName,
            status: row.status,
            userId: row.feiShuOpenId
          }];
          // console.log(row);
          this.admin.roleIdList = [];
          if (row.roleList.length > 0) {
            row.roleList.forEach(item => {
              this.admin.roleIdList.push(item.id);
            });
          }
          this.admin.feiShuOpenId = row.feiShuOpenId;
          this.admin.status = row.status ? 1 : 0;
          this.updateQuery.id = row.id;
          // console.log(this.admin);
          this.dialogVisible = true;
          this.isEdit = true;
        } else {
          this.$message({
            type: 'error',
            message: '无权限操作'
          });
        }
      },
      handleDialogConfirm() {
        // console.log(this.admin);
        // this.$confirm('是否要确认?', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
          if (this.isEdit) {
            this.updateQuery.note = this.admin.note;
            this.updateQuery.roleIdList = this.admin.roleIdList;
            this.updateQuery.status = this.admin.status;
            sysUpdate(this.updateQuery).then(response => {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          } else {
            sysAdd(this.admin).then(response => {
              this.$message({
                message: '添加成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          }
        // })
      },
      getList() {
        this.listLoading = true;
        sysList(this.listQuery).then(response => {
          // console.log('888888', response);
          this.listLoading = false;
          this.list = response.data.list;
          this.total = response.data.total;
        });
      },
      getAllRoleList() {
        fetchAllRoleList().then(response => {
          this.allRoleList = response.data;
        });
      },
    }
  }
</script>
<style></style>


